<?php

require_once('lib/status.php');


/**
 * @return toutes les saisons
 */
function season_get_all()
{
	$sql = 'select s.id, s.year, s.created_at, s.created_by, m.name as creator_name, m.firstname as creator_firstname
	        from Season s
			join Member m on m.id = s.created_by
			order by s.year desc';
	return sql_query($sql);
}


/**
 * Mettre en forme le champ "year" d'une saison
 * @return "year / year + 1"
 */
function season_print($season)
{
	return $season['year'].'/'.($season['year'] + 1);
}


/**
 * @return saison courante
 */
function season_get_current()
{
	$sql = 'select id, year, created_at
	        from Season
	        where year = (select max(s2.year) from Season s2);';
	$data = sql_query($sql);
	return mysql_fetch_assoc($data);
}


/**
 * Activer la saison suivante
 * - créé la saison year + 1
 * - tous les membres "WAITING_MEMBER" deviennent "CANCELED"
 * - tous les membres "MEMBER" deviennent "OLD_MEMBER"
 */
function season_active_next()
{
	$ok = true;
	$admin_id = intval($_SESSION['id']);
	$now = time();
	// migration waiting_member -> canceled
	$canceled_id = status_get_from_code('CANCELED');
	$waiting_member_id = status_get_from_code('WAITING_MEMBER');

	$sql = 'insert into MemberStatusHistory (user_id, status_id, created_at, creator_id)
			  select m.id, '.$canceled_id.', '.$now.', '.$admin_id.'
			  from Member m
			  where m.status_id  = '.$waiting_member_id.';';
	$ok &= sql_query($sql);

	$sql = 'update Member
			  set status_id = '.$canceled_id.', date_pre_registration  = 0
			  where status_id = '.$waiting_member_id.';';
	$ok &= sql_query($sql);

	// migration member -> old_member
	$old_member_id = status_get_from_code('OLD_MEMBER');
	$member_id = status_get_from_code('MEMBER');

	$sql = 'insert into MemberStatusHistory (user_id, status_id, created_at, creator_id)
			  select m.id, '.$old_member_id.', '.$now.', '.$admin_id.'
			  from Member m
			  where m.status_id = '.$member_id.';';
	$ok &= sql_query($sql);

	$sql= 'update Member
			 set status_id = '.$old_member_id.'
			 where status_id = '.$member_id.';';
	$ok &= sql_query($sql);

	// création de la saison
	$sql = 'insert into Season (year, created_at, created_by)
			  values ((select MAX(s2.year) + 1 from Season s2), '.$now.', '.$admin_id.')';
	$ok &= sql_query($sql);
	return $ok;
}
